{% extends "base.html" %}

{% block title %}Inline Formset using Autocomplete{% endblock %}

{% block extrahead %}
{{ formset.media }}
<script type="text/javascript">
    $(function() {
        $('#id_orders_table tbody tr').formset({
            // For inline formsets, be sure to set the prefix, as the default prefix
            // ('form') isn't correct.
            // Django appears to generate the prefix from the lowercase plural
            // name of the related model, with camel-case converted to underscores.
            prefix: 'ordered_items',
            added: function(row) {
                var txt = row.find('.autocomplete-me');
                // Event handlers are cloned with each new form, so we first unbind
                // all autocomplete handlers on the textbox:
                txt.unbind();
                // Calling "makeAutocomplete" adds a brand-new set of handlers:
                makeAutocomplete(txt);
            }
        })
    })
</script>
<style type="text/css">
    .delete-row {
        margin-left:5px;
    }
</style>
{% endblock %}

{% block content %}
<div>
    <div class="entry">
        <form method="post" action="">
            {{ form.as_p }}
            <h2>Order details</h2>
            <table id="id_orders_table" border="0" cellpadding="0" cellspacing="5">
                <thead>
                    <tr>
                        <th scope="col">Product</th>
                        <th scope="col">Quantity</th>
                    </tr>
                </thead>
                <tbody>
                    {% for form in formset.forms %}
                    <tr id="{{ form.prefix }}-row">
                        <td>
                            {{ form.order.as_hidden }}
                            {{ form.product }}
                        </td>
                        <td>{{ form.quantity }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            <p>
                {{ formset.management_form }}
                <input type="submit" value="Submit" />
            </p>
        </form>
    </div>
</div>
{% endblock %}

{% block sidebar %}
<p>
    This autocomplete example is supposed to show one possible use for the optional "added" and
    "removed" callbacks. I know it's not user-friendly to select a product name and have a strange
    number "magically" appear -- believe me, I wouldn't do that in production code :)
</p>
<p>
    The original code I extracted this from was a bit more complicated (it allowed users specify
    search criteria used to create ad-hoc groups). Rather than use that, I decided to base this
    on the <a href="{% url example_inline_formset %}">inline formset example</a>.
</p>
{% endblock %}
